import * as React from 'react';
import { observer } from 'mobx-react';
import { Form, Input, DatePicker, Button, Table, Col, Select, message, Switch } from 'antd';
import * as TinyMCE from 'react-tinymce';

import { ImageUploader } from '../../../../components/ImageUploader';
import { EventModel } from '../../../../../model/assets/standard/EventModel';
import {CREATE_SUCCESS_REDIRECT_DELAY} from "../../../../../service/Config";

const FormItem = Form.Item;
const Option = Select.Option;
const InputGroup = Input.Group;

const formItemLayout = {
    labelCol: { span: 6 },
    wrapperCol: { span: 14 },
};
const tailFormItemLayout = {
    wrapperCol: {
        span: 14,
        offset: 6,
    },
};

interface EventEditorState {
    store?: EventModel;
    coverImageFileList?: any[];
    slidesFileList?: any[];
}

@observer
export class EventEditor extends React.Component<any, EventEditorState> {

    constructor(props) {
        super(props);
        this.initState();
    }

    private isEditMode = this.props.route.path !== 'event/create';

    initState() {
        let store: EventModel;

        if (!this.isEditMode) { // 创建
            store = new EventModel();
        }
        else { // 编辑
            store = new EventModel(this.props.params.id);
            store.fetchData().catch(res => {
                message.error(`数据请求失败`, 2.5);
            });
        }

        this.state = {
            store,
            coverImageFileList: null,
            slidesFileList: null,
        };
    }

    private onSubmit = () => {
        this.state.store.save().then(
            res => message.success(res.message, CREATE_SUCCESS_REDIRECT_DELAY, () => {
                if (!this.isEditMode) {
                    location.href = '#/content/assets/event/manager'
                }
            }),
            err => message.error(err.message, 2.5)
        );
    }

    private renderCoverImageUploader() {
        var {store, coverImageFileList} = this.state;
        var data = store.data;
        var onChange = (fileList) => this.setState({ coverImageFileList: fileList });
        var onUpdate = (fileList) => data.coverImageUrl = fileList.length ? fileList[0].url : "";

        if (!coverImageFileList && data.coverImageUrl) {
            coverImageFileList = [{
                uid: -1,
                url: data.coverImageUrl
            }];
        }

        return <ImageUploader fileList={coverImageFileList} onChange={onChange} onUpdate={onUpdate} />;
    }

    private renderTags() {
        var store = this.state.store;
        var data = store.data;

        return data.tags.map((tag, index) => {
            return <Input.Group size="large" key={index}>
                <Col span={8}>
                    <Input value={tag} onChange={e => data.tags[index] = e.target['value']} />
                </Col>
                <Col span={4}>
                    <Button shape="circle" icon="plus" onClick={() => store.addTagAt(index + 1)} />
                    {data.tags.length > 1 && <Button shape="circle" icon="delete" onClick={() => store.removeTagAt(index)} />}
                </Col>
            </Input.Group>
        });
    }

    render() {
        var {store} = this.state;
        var data = store.data;

        return <Form horizontal>
            <FormItem
                {...formItemLayout}
                label="活动名称"
                required
                validateStatus={store.nameValid ? 'success' : 'error'}
            >
                <Input placeholder="请输入活动名称，最多显示14个字，活动名称不能重复" value={data.name} onChange={e => data.name = e.target['value']} />
            </FormItem>
            <FormItem
                {...formItemLayout}
                label="主办方名称"
                required
                validateStatus={store.hostNameValid ? 'success' : 'error'}
            >
                <Input placeholder="请输入店铺/品牌名称/主办方名称" value={data.hostName} onChange={e => data.hostName = e.target['value']} />
            </FormItem>
            <FormItem
                {...formItemLayout}
                label="封面图"
                extra="图片建议尺寸：750像素*387像素，长方形"
                required
            >
                {this.renderCoverImageUploader()}
            </FormItem>
            <FormItem
                {...formItemLayout}
                label="区域"
            >
                <Input placeholder="请输入当前活动所覆盖区域，可以是全国，可以是某个地区" value={data.district} onChange={e => data.district = e.target['value']} />
            </FormItem>
            <FormItem
                {...formItemLayout}
                label="现价"
            >
                <InputGroup size="large">
                    <Col span={4}>
                        <Input type="number" placeholder="00.00" value={data.price.value} onChange={e => data.price.value = e.target['value']} />
                    </Col>
                    <Col span={2}>
                        元/
                    </Col>
                    <Col span={5}>
                        <Input placeholder="份,人,个,次,张(数量单位)" value={data.price.unit} onChange={e => data.price.unit = e.target['value']} />
                    </Col>
                </InputGroup>
            </FormItem>
            <FormItem
                {...formItemLayout}
                label="热门标签"
                extra="至少提供一个标签"
                required
                validateStatus={store.tagsValid ? 'success' : 'error'}
            >
                {this.renderTags()}
            </FormItem>
            <FormItem
                {...formItemLayout}
                label="跳转链接"
                required
                validateStatus={store.urlValid ? 'success' : 'error'}
            >
                <Input placeholder="http://example.com" value={data.url} onChange={e => data.url = e.target['value']} />
            </FormItem>
            <FormItem
                {...formItemLayout}
                label="是否编辑活动详情页"
                required
            >
                <Switch defaultChecked={!data.isOutLink} onChange={checked => data.isOutLink = !checked} />
            </FormItem>
            {this.renderContentEditor()}
            <FormItem {...tailFormItemLayout}>
                <Button type="primary" size="large" onClick={this.onSubmit} loading={store.isSubmiting} style={{ marginRight: 10 }}>保存</Button>
                <Button size="large" onClick={() => location.href = '#/content/assets/event/manager'}>返回列表</Button>
            </FormItem>
        </Form>;
    }

    private renderContentEditor() {
        var {data} = this.state.store;

        if (data.isOutLink) {
            return;
        }

        return <div>
            <FormItem
                {...formItemLayout}
                label="跳转按钮名称"
                required
            >
                <Input value={data.outLinkDesc} onChange={e => data.outLinkDesc = e.target['value']} />
            </FormItem>
            <FormItem
                {...formItemLayout}
                label="多少人喜欢过"
                required
            >
                <Input type="number" value={data.likeCount} onChange={e => data.likeCount = e.target['value']} />
            </FormItem>
            <FormItem
                {...formItemLayout}
                label="详情页轮播图"
                extra="【图片建议尺寸：750像素*468像素，大小120KB以内，长方形，最多5张】"
                required
            >
                {this.renderSlidesUploader()}
            </FormItem>
            <FormItem
                {...formItemLayout}
                label="电话"
            >
                <Input type="string" value={data.tel} onChange={e => data.tel = e.target['value']} />
            </FormItem>
            <FormItem
                {...formItemLayout}
                label="地址"
            >
                <Input type="string" value={data.address} onChange={e => data.address = e.target['value']} />
            </FormItem>
            <FormItem
                {...formItemLayout}
                label="坐标"
            >
                <Input type="string" value={data.coordinates ? data.coordinates.join(',') : ""} onChange={e => data.coordinates = e.target['value'].split(",")} />
                <a href="http://lbs.qq.com/tool/getpoint/" target="_blank">坐标拾取器</a>
            </FormItem>
            <FormItem
                {...formItemLayout}
                label="推荐理由"
                required
            >
                <TinyMCE
                    content={data.recommendReason}
                    config={{
                        plugins: 'link code',
                        toolbar: 'undo redo | bold italic | alignleft aligncenter alignright | code',
                        language: 'zh_CN',
                    }}
                    onChange={(e) => data.recommendReason = e.target.getContent()}
                />
            </FormItem>
            <FormItem
                {...formItemLayout}
                label="活动内容"
            >
                <TinyMCE
                    content={data.content}
                    config={{
                        plugins: 'link image code',
                        toolbar: 'undo redo | bold italic | alignleft aligncenter alignright | code',
                        language: 'zh_CN',
                    }}
                    onChange={(e) => data.content = e.target.getContent()}
                />
            </FormItem>
        </div>;
    }

    private renderSlidesUploader() {
        var {store, slidesFileList} = this.state;
        var data = store.data;
        var onChange = (fileList) => this.setState({ slidesFileList: fileList });
        var onUpdate = (fileList) => data.slides = fileList.map(e => e.url);

        if (!slidesFileList && data.slides && data.slides[0]) {
            slidesFileList = data.slides.map((slide, index) => ({ uid: -index - 1, url: slide }))
        }

        return <ImageUploader limit={5} fileList={slidesFileList} onChange={onChange} onUpdate={onUpdate} />;
    }
}